<?php
/**
 * 单表模型管理
 * 自动生成 CURD 控制器
 * 自动生成 对应的 view 视图
 * 自动创建数据库表
 * 自动生成菜单导航
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use app\common\model\NewModule as NewModuleModel;
use think\facade\Db;

class NewModule extends AdminBase
{


    //模型创建管理
    function Index(){
        if($this->request->isAjax()){
            $param = $this->request->param();
            $model = new NewModuleModel();
            $list = $model->getList($param);
            foreach ($list as $k=>$v){
                $list[$k]['name'] = $v->name_text;
                if($v->output_time){
                    $list[$k]['output_time'] = date('Y-m-d H:i:s',$v->output_time);
                }else{
                    $list[$k]['output_time'] = '--';
                }
            }
            $this->success('ok',"",$list);
        }else{
            return view('',[]);
        }

    }

    function edit(){
        $model = new NewModuleModel();
        if($this->request->isAjax()){
            //保存数据
            $param = $this->request->param();
            try {
                $model->saveTable($param);
            }catch (\Exception $e){
                if($e->getCode()==100){
                    //是否需要删除旧的模块 并保存为新模块
                    $this->success($e->getMessage(),"","isdel");
                }else{
                    $this->error($e->getMessage());
                }
            }
            $this->success('保存成功');
        }
        $id = input('id');
        $field = 'id,name,table_name,file_name,is_edit_new,table_comment,is_model';
        $data = $model->where('id',$id)->field($field)->find()->toArray();
        $assign = [
            'id'=>$id,
            'data'=>$data,
            'fieldType'=>NewModuleModel::$fieldType,
        ];
        return view('',$assign);
    }

    //删除已经删除的模型
    function delete(){
        $model = new NewModuleModel();
        $id = input('id');
        $isApi = input('isApi')?:0;
        try {
            $info = $model->deleteModule($id,$isApi);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }

    /**
     * 获取模块table信息
     */
    function getInfo(){
        $id = input('id');
        if(empty($id)){
            $this->error("请输入ID");
        }
        $model = new NewModuleModel();
        $data = $model->getInfo($id);
        $this->success("ok",'',$data);
    }

    //提交生成模型文件
    function generate(){
        $id = input('id');
        $isCover = input('isCover');
        $isApi = input('isApi');
        $coverList = input('coverList');
        if(empty($id)){
            $this->error("请输入ID");
        }
        $model = new NewModuleModel();
        try {
            $info = $model->generate($id,$isCover,$isApi,$coverList);
            $this->apiSuccess("生成成功，请刷新后测试模块功能！");

        }catch (\Exception $e){
            if($e->getCode()==101){
                $this->apiError($e->getMessage(),"is_existence",1);
            }else{
                $this->apiError($e->getMessage());
            }
        }
        $this->apiError('请求失败，系统错误！');
    }

    //更新数据库的表关联信息
    function syncTable(){
        $config = config('database');
        $config = $config['connections'][$config['default']];
        //表前缀
        $prefix = $config['prefix'];
        //表名
        $table_schema =$config['database'];
        $sql = "select table_name as 'table_name',table_comment as 'table_comment' from information_schema.tables where table_schema='{$table_schema}'";
//        $sql2 = "SHOW COLUMNS FROM [table_name] FROM {$table_schema}";
        $sql2 = "SELECT COLUMN_NAME as 'Field',column_comment as 'column_comment' ,column_type as 'Type' ,column_key as 'column_key'  FROM information_schema.columns  WHERE table_schema = '{$table_schema}' and table_name = '[table_name]'";
        $tableList = Db::query($sql);
//        dump($tableList);exit;
        $model = new NewModuleModel();
        foreach ($tableList as $k=>$v){
            $table_name = $v['table_name'];
            $name = str_replace($prefix,'',$table_name);
            if(!in_array($name,NewModuleModel::$systemTable)){
                $sql3 = str_replace('[table_name]',$table_name,$sql2);
                $fieldList = Db::query($sql3);

                $fieldList_new = [];
                foreach ($fieldList as $ks=>$vs){
                    $name = $vs['column_comment'];
                    if($name){
                        $name = str_replace(',',' ',$name);
                        $name = explode(' ',$name)[0];
                    }
                    //默认选项都是开启状态
                    $is_edit = $show_list  = 1;
                    $is_time = 0;
                    //id 不需要编辑
                    if($vs['Field']=='id'){
                        $is_edit = false;
                    }
                    //时间字段 默认不可编辑
                    if(strpos($vs['Field'],"_time")){
                        $is_time = 1;
                        $is_edit = 0;
                    }
                    $fieldList_new[] = [
                        'field'=>$vs['Field'],
                        'type'=>$vs['Type'],
                        'name'=>$name,
                        'column_comment'=>$vs['column_comment'],
                        'is_edit'=>$is_edit,
                        'show_list'=>$show_list,
                        'is_time'=>$is_time,
                    ];
                }
                //查询记录是否存在
                $info = $model->where(['table_name'=>$table_name])->find();
                $time = time();
                $upData = [
                    'field'=>json_encode($fieldList_new),
                    'field_text'=>$info->id ? $info['field_text']: json_encode($fieldList_new),
                    'file_number'=>count($fieldList_new),
                    'up_time'=>$time,
                    'table_comment'=>$v['table_comment'],
                ];
                if(!$info['name']){
                    $upData['name'] = $v['table_comment']; //默认是表备注名
                }
                if(!$info['file_name']){
                    $upData['file_name'] = NewModuleModel::getFileName($table_name);
                }
                if($info){
                    $model->where(['id'=>$info['id']])->update($upData);
                }else{
                    $upData['table_name'] = $table_name;
                    $upData['create_time'] = $time;
                    $model->insertGetId($upData);
                }
            }
        }
        $this->success('同步成功！');
    }
}